<template>
    <div style="background-color: #fff;">
      <main-layout>
        <el-form ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px" size="small" style="width: 500px;">
            <el-form-item label="农场名称" prop="farmName">
                <el-input v-model="formdata.farmName" placeholder="请输入农场名称"/>
            </el-form-item>
            <el-form-item label="公司名称" prop="companyId" class="relativeBox">
                <!-- <el-select class="small-el-input__inner" popper-class="samll-el-select-dropdown__list" v-model="formdata.companyId" clearable placeholder="请选择公司" style="width: 100%;">
                    <el-option v-for="dt in companys" :key="dt.companyId" :value="dt.companyId" :label="dt.companyName" />
                </el-select> -->
                <company-select v-model="formdata.companyId" :disabled="userStore.userInfo.roleId!=1" className="small-el-input__inner" popperClass="samll-el-select-dropdown__list" />
                <div class="afterSlot" v-if="userStore.userInfo.roleId==1"><el-icon @click="openAdd"><Plus /></el-icon></div>
            </el-form-item>
            <el-form-item label="联系人" prop="contacts">
                <el-input v-model="formdata.contacts" placeholder="请输入联系人姓名"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactsPhone">
                <el-input v-model="formdata.contactsPhone" placeholder="请输入联系电话"/>
            </el-form-item>

            <!-- <el-form-item label="状态" prop="isEnable" v-if="farmId">
              <el-select v-model="formdata.isEnable" clearable placeholder="请选择状态" style="width: 100%;">
                <el-option :value="true" label="启用" />
                <el-option :value="false" label="禁用" />
              </el-select>
            </el-form-item> -->

            <el-form-item label="地理位置" prop="locationName">
                <el-input v-model="formdata.locationName" placeholder="请输入地理位置"/>
            </el-form-item>

            <el-form-item label="" prop="">
              <div style="width:450px;height:400px;position: relative;">
                <tencent-map ref="mapRef" @loading_completed="mapLoaded" @on_click="getAddress" :showControl="false"/>
                <div class="sslistbox">
                  <map-keyword-tips @selected="getAddress"/>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="详细地址" prop="locationDetail">
                <el-input v-model="formdata.locationDetail" placeholder="请输入详细地址"/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="save">保存</el-button>
              <el-button @click="close">取消</el-button>
            </el-form-item>
        </el-form>
        <add-company v-if="addFlag" v-model:show="addFlag" title="添加公司" @success="setCompany" :editData="editData"/>
      </main-layout>
  
    </div>
  </template>
  
  <script setup>
  // 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
  
  import { nextTick, ref, reactive,watch, onActivated,onMounted} from 'vue'
  import{useRouter,useRoute} from "vue-router"

  import {getCompanyList,addFarm,getFarmDetail,editFarm} from '@/api/system'

  import { useUserStore } from '@/pinia/modules/user'
  import { emitter } from '@/utils/bus.js'
  import mainLayout from '@/components/custom/mainLayout.vue'
  import tencentMap from '@/components/custom/tencentMap.vue'
  import mapKeywordTips from '@/components/custom/mapKeywordTips.vue'
  import addCompany from './components/addCompany.vue'
  import companySelect from '@/components/custom/companySelect.vue'
  import { message } from '@/utils/element'
 

  const router = useRouter()
  const route = useRouter()
  const userStore = useUserStore()
  
  const mapRef = ref(null)
  const addFlag = ref(false)
  const editData = ref({})
  const farmId = ref('')
  const formdata = ref({})
  const ruleFormRef = ref(null)
  const companys = ref([])
  
  onMounted(async ()=>{

    formdata.value.companyId = userStore.userInfo.companyId

    get_company_list()
    // await nextTick()
    // const ggg =await mapRef.value.address_convert_to_latLng('广州市')
    // console.log("ggg:",ggg)
    // 设置鼠标绘图
   // mapRef.value.drawMap()
    //console.log("route.query:",route.currentRoute.value.query.id)
    farmId.value = route.currentRoute.value.query.id
    if(farmId.value){
      document.title = '编辑农场-种植生产管理智能决策系统'
      const res = await getFarmDetail(farmId.value)
      if(res.code == 0){
        formdata.value = res.data
        // 设置中心点
        mapRef.value.setCenter(res.data.locationLatitude,res.data.locationLongitude)
        // 标记
        mapRef.value.setMultiMarker(res.data.locationLatitude,res.data.locationLongitude)
      }
    }
  })
  
  // 验证手机号
  const checkPhone = (rule, phone, callback) => {
      const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phone)) {
          return callback(new Error('手机号输入有误'))
      } else {
          callback() // 验证通过
      }
  }
  const rules = reactive({
    farmName: [
        { required: true, message: '请输入农场名称', trigger: 'blur' },
        //{ min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    companyId:[
        { required: true, message: '请选择公司', trigger: 'blur' },
    ],
    contacts:[
        { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    ],
    contactsPhone:[
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { validator:checkPhone, trigger: 'blur' }
    ],
    locationName:[
        { required: true, message: '请输入地理位置', trigger: 'blur' },
    ],
    locationDetail:[
        { required: true, message: '请输入详细地址', trigger: 'blur' },
    ]
  })

  const save = async ()=>{
    await ruleFormRef.value.validate(async(valid, fields) => {
        if (valid) {
          let res = {}
          if(farmId.value){
            res = await editFarm(formdata.value)
          }else{
            res= await addFarm(formdata.value)
          }
          if(res.code ==0){
            message('数据提交成功',2)
            close()  // 关闭当前页
            emitter.emit('reload') // 刷新页面
          }
        } else {
          message('请正确填写表单',3)
        }
    })
  }
  
  const mapLoaded = (mapobj)=>{
    console.log("mapobj:",mapobj)
  }

  const getAddress = (detail)=>{
    //console.log("选择：",detail)
    formdata.value.locationName = detail.province+detail.city+detail.district
    formdata.value.locationDetail = detail.address
    formdata.value.locationLatitude = detail.location.lat
    formdata.value.locationLongitude = detail.location.lng
    // 设置中心点
    mapRef.value.setCenter(detail.location.lat,detail.location.lng)
    // 标记
    mapRef.value.removeAllMarker()
    mapRef.value.setMultiMarker(detail.location.lat,detail.location.lng)
  }


  const openAdd = ()=>{
    //editData.value = {}
    addFlag.value = true
  }

  const get_company_list = async ()=>{
    const res = await getCompanyList({page: 1, limit: 100})
    if(res.code ==0 ){
        companys.value = res.data
    }
}

  const setCompany = async (id)=>{
    await get_company_list()
    formdata.value.companyId = id
  }
  
  const close = ()=>{
    emitter.emit('closeThisPage')
  }
  
  </script>
  
  <style lang="scss" scoped>
    .sslistbox{
        position: absolute;
        z-index: 1000;
        left: 10px;
        top: 10px;
    }
  </style>
  